package utilities.service;

import java.util.Date;
import utilities.BDSQLiteHelper;
import utilities.Preferencias;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;

public class InsertarLlamadas extends Activity{
	String TAG = "PEI";
	Context context;
	Preferencias pref;
	Long fechaTope;
	
	public InsertarLlamadas(Context context) {
		pref = new Preferencias(context);
		this.context = context;
		getCallDetails();
	}
	
	public void getCallDetails() {
		BDSQLiteHelper usdbh = new BDSQLiteHelper(context, "DB_PEI", null, 1);
		SQLiteDatabase db = null,dbllam=null;
		String phNumber;
		String callDate;
		Date callDayTime;
		int _id,idc=-1;
		String nombre="";
		String callDuration;
		Object[] obj = null;
		
		long fec;
		Date dPresup,dActual;
		//Si la fecha actual es menor a la del presupuesto, no hacemos nada
		if(pref.getPref(Preferencias.EXISTE_PRESUPUESTO, Preferencias.NO).equals(Preferencias.SI)){
			fec = Long.parseLong(pref.getPref(Preferencias.FECHA_INI_PRESUP, "-1"));
			dPresup = new Date(fec);
			dActual = new Date();
			if(dActual.before(dPresup)) return;
		}
		
		fechaTope = Long.parseLong(pref.getPref(Preferencias.FECHA_CREACION_PLAN, ""));

		//Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null);
		Cursor managedCursor = context.getContentResolver().query( CallLog.Calls.CONTENT_URI,
				null,
				//Obtenemos unicamente las llamadas salientes cuya duracion sea mayor a 0 segundos
				CallLog.Calls.TYPE + " = " +CallLog.Calls.OUTGOING_TYPE + " AND "+ CallLog.Calls.DURATION + " > 0 AND "+CallLog.Calls.DATE+" >= "+fechaTope,
				null, 
				//ordenamos los registros en orden ascendente segun la fecha
				CallLog.Calls.DATE + " DESC");
		int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); 
		int date = managedCursor.getColumnIndex( CallLog.Calls.DATE);
		int duration = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
		int idtmp = managedCursor.getColumnIndex( BaseColumns._ID);
		
		try{
			
		db = usdbh.getWritableDatabase();
		dbllam = usdbh.getReadableDatabase();
		Cursor cllam;
		while ( managedCursor.moveToNext() ) {
			obj = null;
			phNumber = managedCursor.getString( number );
			callDate = managedCursor.getString( date );
			callDayTime = new Date(Long.valueOf(callDate));			
			callDuration = managedCursor.getString( duration );
			_id = managedCursor.getInt( idtmp );
			obj = getContact(phNumber);

			//si la llamada ya existe no la metemos a la tabla, si retorna algo, saltamos l registro
			cllam = dbllam.query("PEI_LLAMADA", new String[]{"ID_LLAMADA"}, "ID_LLAMADA = "+_id, null, null, null, null);
			if(cllam.moveToFirst()) continue; 
			
			if(obj != null){//En la posicion 0 vendra el nombre
				nombre = (String)obj[0];//En la 1 ID del contacto
				idc = (Integer)obj[1];
			}
				db.execSQL("INSERT INTO PEI_LLAMADA(ID_LLAMADA,NUMERO,DURACION,PROVEEDOR_DESTINO,NOMBRE_CONTACTO,FECHA,ID_CONTACTO,EST_ESTADO) " +
						"VALUES ('"+_id+"','"+phNumber+"','"+callDuration+"','"+getCompania(phNumber)+"','"+nombre+"','"+callDayTime.getTime()+"','"+idc+"',1)");
				
				calcular(Integer.parseInt(callDuration),getCompania(phNumber));
						
		}
		}catch(Exception e){
			e.printStackTrace();
			Log.i(TAG,e.getMessage());
		}
		finally{
			db.close();
			dbllam.close();
		}
		managedCursor.close();
		
	}
	
	/**
	 * @author Fabrizzio: Metodo para obtener el nombre del contacto
	 * @param numero telefonico del contacto que se desea obtener
	 * @return nombre del contacto, sino existe en 
	 */
	public Object[] getContact(String number) {
		Object[] obj = new Object[]{null,null};
		int idc;
    	String[] columns = new String[] {
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER,
				ContactsContract.Contacts.PHOTO_ID,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    	Uri uriContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		Cursor cur = context.getContentResolver().query(
				uriContacts, 
				columns,
				Phone.NUMBER + " LIKE '%"+ number+"'", 
				null, 
				null
		);

        if (cur.moveToFirst()) {
            obj[0] = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            idc = cur.getInt(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
            obj[1] = idc;
            return obj;
        }
        return null;
	}
	
	public String getCompania(String number) {
		int n;
		String num = number.replaceFirst("-", "");
		num = num.replaceFirst("503", "");
		num = num.replaceFirst("\\+", "");
		if(num.length()!=8 || num.charAt(0)!='7'){
			return "Desconocido";
		}
        num = num.substring(0,4);
        n = Integer.parseInt(num);
        
        if(((n>=7000)&&(n<=7099))||                  
             ((n>=7600)&&(n<=7669))||
             ((n>=7687)&&(n<=7690))||
             ((n>=7740)&&(n<=7759))||
             ((n>=7805)&&(n<=7809))||
             ((n>=7840)&&(n<=7844))||
             ((n>=7850)&&(n<=7869))||
             ((n>=7950)&&(n<=7969))||
             ((n>=7985)&&(n<=7989))){
                        return "CLARO";           
        }
                                                
        if(((n>=7300)&&(n<=7399))||                                        
                ((n>=7400)&&(n<=7449))||                                                                           
                ((n>=7460)&&(n<=7469))||
                ((n>=7695)&&(n<=7698))||
                ((n>=7760)&&(n<=7779))||
                ((n>=7970)&&(n<=7979))){
                 return "DIGICEL";                         
        }

        if(((n>=7100)&&(n<=7199))||
                  ((n>=7450)&&(n<=7459))||
                  ((n>=7691)&&(n<=7694))||
              ((n>=7700)&&(n<=7719))||
              ((n>=7780)&&(n<=7784))||
              ((n>=7790)&&(n<=7794))||
              ((n>=7810)&&(n<=7839))||
              ((n>=7845)&&(n<=7849))||
              ((n>=7990)&&(n<=7999))){
                return "MOVISTAR";
        }
        
        if(((n>=7200)&&(n<=7299))||
             ((n>=7470)&&(n<=7499))||
             ((n>=7500)&&(n<=7599))||                        
             ((n>=7670)&&(n<=7679))||
             ((n>=7680)&&(n<=7683))||
             ((n>=7720)&&(n<=7739))||
             ((n>=7785)&&(n<=7789))||
             ((n>=7795)&&(n<=7799))||
             ((n>=7870)&&(n<=7899))||
             ((n>=7900)&&(n<=7949))){
                        return "TIGO";

                }
        return "Desconocido";
	}
	
	
	private void calcular(int s,String comp){
		double tarifaExt=0,tarifaLoc=0;
		double totalConsumido = Double.parseDouble(pref.getPref(Preferencias.CONSUMO_TOTAL, "0"));
		int minInc=0,totalMinuto = Integer.parseInt(pref.getPref(Preferencias.MINUTOS_CONSUMIDOS, "0"));
		String tplan="";
		String proveedorSer="";
		double sec=s,cons=60;
		double minutos = Math.ceil(sec/cons);
		BDSQLiteHelper usdbh = new BDSQLiteHelper(context, "DB_PEI", null, 1);
		SQLiteDatabase db = null;
		try{
			db = usdbh.getReadableDatabase();
			Cursor c_plan = db.query("PEI_PLAN", new String[] {"TARIFA_EXTERNA","TARIFA_LOCAL","TIPO_PLAN","PROVEEDOR_SERVICIOS","MINUTOS_INCLUIDOS"}, null, null, null, null, null);
			if(c_plan.moveToFirst()){
				tarifaExt = Double.parseDouble(c_plan.getString(0));
				tarifaLoc =  Double.parseDouble(c_plan.getString(1));
				tplan = c_plan.getString(2);
				proveedorSer = c_plan.getString(3);
				minInc = c_plan.getInt(4);
			}
			int tmpTotal =totalMinuto; 
			totalMinuto+=(int)minutos;
			if(tplan.equalsIgnoreCase("Postpago")){//Si es postpago, tiene minutosIncluidos
				int cantACobrar = totalMinuto-minInc; 
				if(cantACobrar>0 && tmpTotal<minInc){
					if(proveedorSer.equalsIgnoreCase(comp))//tarifa entre misma compania
						totalConsumido = totalConsumido+cantACobrar*tarifaLoc;
					else//tarifa enter difernte compania
						totalConsumido = totalConsumido+cantACobrar*tarifaExt;
				}
				else if(tmpTotal>=minInc){
					if(proveedorSer.equalsIgnoreCase(comp))totalConsumido = totalConsumido+minutos*tarifaLoc;
					else totalConsumido = totalConsumido+minutos*tarifaExt;
				}
			}
			else{
				if(proveedorSer.equalsIgnoreCase(comp))//tarifa entre misma compania
					totalConsumido = totalConsumido+minutos*tarifaLoc;
				else//tarifa enter difernte compania
					totalConsumido = totalConsumido+minutos*tarifaExt;
			}
			float tmp = (float) 0.00;
			tmp = (float) totalConsumido;
			pref.setPref(Preferencias.CONSUMO_TOTAL, tmp+"");
			pref.setPref(Preferencias.MINUTOS_CONSUMIDOS, totalMinuto+"");
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			db.close();
		}
	}
	


}
